package com.nightsoul.shirotest.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class MyRealm2 extends AuthorizingRealm {


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String algorithmName = "md5";
		String username = (String) token.getPrincipal();
		String password = new String((char[]) token.getCredentials());
		String salt1 = username;
		String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
		int hashInterations = 2;

		String salt = salt1 + salt2;
		System.out.println("salt=" + salt);
		SimpleHash hash = new SimpleHash(algorithmName, password, salt, hashInterations);
		String encodedPassword = hash.toHex();
		System.out.println("encodedPassword=" + encodedPassword);


		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, encodedPassword, super.getName());
		authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(salt));
		return authenticationInfo;
	}

	public static void main(String[] args) {
		String algorithmName = "md5";
		String username = "liu";
		String password = "123";
		String salt1 = username;
		String salt2 = new SecureRandomNumberGenerator().nextBytes().toHex();
		int hashInterations = 2;

		SimpleHash hash = new SimpleHash(algorithmName, password, salt1 + salt2, hashInterations);
		String encodedPassword = hash.toHex();
		System.out.println(encodedPassword);
	}

}
